<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    :modal="false"
    top="100px"
    :close-on-click-modal="false"
    class="component-customizereason-sku-select-components"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"

      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName')">
        <el-input
          v-model.trim="prodName"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('product.shopCategories')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          style="width: 180px"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{
            $t("order.query")
          }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{
            $t("shop.resetMap")
          }}
        </div>
      </el-form-item>
    </el-form>
    <div>{{ $t("dataAnaly.chosen") }}{{ $t("home.product") }}:{{ totalSelectCount }}</div>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        border
        style="width: 100%"
      >
        <el-table-column
          header-align="center"
          align="center"
          width="50"
        >
          <!--自定义选择-->
          <template #header>
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            />
          </template>
          <template #default="scope">
            <el-checkbox
              :key="scope.row.skuId"
              v-model="scope.row.check"
              @change="handleCheckedCitiesChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="380"
          :label="$t('product.prodInfo')"
        >
          <template #default="scope">
            <div class="prod-info-container">
              <div class="prod-image">
                <ImgShow
                  :src="scope.row.pic"
                  :img-style="{width:'100px',height:'100px'}"
                  :class-list="['img']"
                />
              </div>
              <div class="prod-name">
                <div class="prod-name-txt">
                  {{ scope.row.prodName }}
                </div>
                <div class="prod-no">
                  {{ scope.row.partyCode }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="prodStatus"
          header-align="center"
          align="center"
          :label="$t('product.status')"
          width="150px"
        >
          <template #default="scope">
            <el-tag
              v-if="scope.row.prodStatus === 0"
              type="warning"
            >
              {{ $t('publics.metLowerShelf') }}
            </el-tag>
            <el-tag
              v-if="scope.row.prodStatus === 1"
              type="success"
            >
              {{ $t('publics.UpperShelf') }}
            </el-tag>
            <el-tag
              v-if="scope.row.prodStatus === 2"
              type="danger"
            >
              {{ $t('publics.violationShelf') }}
            </el-tag>
            <el-tag
              v-if="scope.row.prodStatus === 3"
              type="danger"
            >
              {{ $t('productComm.platformAudit') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="skuName"
          header-align="center"
          align="center"
          :label="$t('stock.spec')"
        >
          <template #default="scope">
            <div class="sku-name-txt">
              {{ scope.row.skuName || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="stocks"
          header-align="center"
          align="center"
          :label="$t('coupon.stock')"
        >
          <template #default="scope">
            <div class="sku-name-txt">
              {{ scope.row.stocks }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="overflow:auto;margin:15px 5px"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
    <template #footer>
      <span>
        <div
          class="default-btn"
          @click="visible = false"
        >{{
          $t("crud.filter.cancelBtn")
        }}</div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="submitProds()"
        >{{
          $t("crud.filter.submitBtn")
        }}</div>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils'
import { reactive } from 'vue'

const emit = defineEmits(['refreshSelectProds'])
const props = defineProps({
  prodType: {
    default: null,
    type: Number // 商品类型
  },
  dataUrl: {
    default: '/sku/pageSku',
    type: String // 商品请求url
  },
  chosenCheckItems: {
    // eslint-disable-next-line vue/require-valid-default-prop
    default: [],
    type: Array // 已选择的数据项
  },
  isMemoryOldData: {
    default: false,
    type: Boolean // 是否记忆已选择的数据项中的数据
  },
  isCompose: {
    default: null,
    type: Number
  }
})

const visible = ref(false)
const dataForm = reactive({
  product: ''
})
const checkAll = ref(false) // 全选状态
const isIndeterminate = ref(false) // 不确定状态
let currentPageCheckCount = 0 // 当前页选中的结点数量
const dataList = ref([])
const prodName = ref('')
let shopCategoryId = null
const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const dataListLoading = ref(false)
const totalSelectCount = ref(0) // 当前选择的商品总数量
let chosenNodesMap = {} // 已选择的结点对象map
let currentCheckNodesMap = {} // 当前选择的结点对象map
const categoryList = ref([])
const selectedCategory = ref([])
const categoryTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})

onMounted(() => {
  const lang = localStorage.getItem('bbcLang')
  categoryTreeProps.label = lang === 'en' ? 'categoryNameEn' : 'categoryName'
})

onActivated(() => {
  init()
})

// 获取数据列表
const init = () => {
  dataListLoading.value = true
  prodName.value = ''
  selectedCategory.value = []
  shopCategoryId = null
  totalSelectCount.value = 0
  chosenNodesMap = {}
  currentCheckNodesMap = {}
  setDefaultCheckedKeys()
  getDataList()
  getCategoryList()
  visible.value = true
}
defineExpose({ init })
const setDefaultCheckedKeys = () => {
  if (props.chosenCheckItems && props.chosenCheckItems.length > 0) {
    props.chosenCheckItems.forEach(node => {
      node = node || {}
      chosenNodesMap[node.skuId] = node
      currentCheckNodesMap[node.skuId] = node
      ++totalSelectCount.value
    })
  }
}
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get'
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}
/**
 * 点击全选按钮
 */
const handleCheckAllChange = () => {
  isIndeterminate.value = false
  totalSelectCount.value = totalSelectCount.value - currentPageCheckCount
  if (checkAll.value) {
    currentPageCheckCount = dataList.value.length
    dataList.value.forEach(item => {
      item.check = true
      currentCheckNodesMap[item.skuId] = item
    })
  } else {
    currentPageCheckCount = 0
    dataList.value.forEach(item => {
      item.check = false
      delete currentCheckNodesMap[item.skuId]
    })
  }
  totalSelectCount.value = totalSelectCount.value + currentPageCheckCount
}
/**
 * 点击行选择按钮
 */
const handleCheckedCitiesChange = (row) => {
  if (row.check) {
    // 勾选
    ++currentPageCheckCount
    ++totalSelectCount.value
    currentCheckNodesMap[row.skuId] = row
  } else {
    // 取消勾选
    --currentPageCheckCount
    --totalSelectCount.value
    delete currentCheckNodesMap[row.skuId]
  }
  setCheckAllVal()
}
const setCheckAllVal = () => {
  checkAll.value = currentPageCheckCount === dataList.value.length
  isIndeterminate.value = currentPageCheckCount > 0 && currentPageCheckCount < dataList.value.length
}
/**
 * 获取商品数据
 */
const getDataList = () => {
  currentPageCheckCount = 0
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          prodName: prodName.value || null,
          prodType: props.prodType,
          shopCategoryId,
          isCompose: props.isCompose
        }
      )
    )
  }).then(({ data }) => {
    totalPage.value = data.total
    if (props.chosenCheckItems) {
      data.records.forEach(item => {
        const skuId = item.skuId
        if (currentCheckNodesMap[skuId]) {
          ++currentPageCheckCount
          item.check = true
        } else {
          item.check = false
        }
      })
    }
    dataList.value = data.records
    setCheckAllVal()
    dataListLoading.value = false
  }).catch(() => {
    dataListLoading.value = false
  })
}
// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}
/**
 * 获取分类id
 */
const handleChange = (val) => {
  shopCategoryId = val[val.length - 1]
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}
/**
 * 清空搜索条件
 */
const clean = () => {
  prodName.value = ''
  shopCategoryId = null
  selectedCategory.value = idList(categoryList.value, shopCategoryId, 'categoryId', 'children').reverse()
}
// 确定事件
const submitProds = () => {
  let selectList = []
  if (props.isMemoryOldData) {
    for (const i in currentCheckNodesMap) {
      const item = currentCheckNodesMap[i]
      if (chosenNodesMap[item.skuId]) {
        selectList.push(chosenNodesMap[item.skuId])
      } else {
        selectList.push(item)
      }
    }
  } else {
    selectList = Object.values(currentCheckNodesMap)
  }
  emit('refreshSelectProds', selectList)
  visible.value = false
}

</script>
<style lang="scss" scoped>
.prods-select-body {
  margin-top: 10px;
}
.prod-info-container {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-content: center;
  height: 70px;
  .prod-image {
    margin-right: 20px;
    width: 70px;
    height: 70px;
    :deep(.img) {
      width: 70px !important;
      height: 70px !important;
    }
  }
  .prod-name {
    width: 260px;
    height: 70px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .prod-name-txt {
      font-size: 14px;
      color: #333333;
      word-break: break-all;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
    .prod-no {
      font-size: 14px;
      color: #333333;
    }
  }
}
.sku-name-txt {
  font-size: 14px;
  color: #333333;
  word-break: break-all;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
</style>
